<template>
	<view class="container">
		<uni-segmented-control :current="currentIndex" :values="items" style-type="text" active-color="#007aff"
			@clickItem="onClickItem" />

		<view v-if="currentIndex === 0">
			<view style="padding-top: 10px;"></view>

			<uni-forms ref="baseForm" :modelValue="jiayouApplyForm" border labelWidth="100px" label-position="left">

				<uni-forms-item label="申请人">
					<view class="text-bg">{{userName}}</view>
				</uni-forms-item>
				<uni-forms-item label="加油时间" required>
					<uni-datetime-picker @click="chuanci()" type="date"
						return-type="string" v-model="jiayouApplyForm.jiayouDate" />
				</uni-forms-item>

				<uni-forms-item label="车牌号" required>
					<picker type="default" :range="chepaiList" @change="chepaiChange">
						<view class="picker-bg">{{chepaiNameStr()}}</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="本次里程" required>
					<uni-easyinput type="number" v-model="jiayouApplyForm.licheng" />
				</uni-forms-item>
				<uni-forms-item label="上次加油行驶里程" required>
					<uni-easyinput type="number" v-model="jiayouApplyForm.lastLicheng" />
				</uni-forms-item>
				<uni-forms-item label="使用记录是否填写" required>
					<uni-data-checkbox v-model="jiayouApplyForm.wanzheng" :localdata="wanzhengStr" />
				</uni-forms-item>
				
				<!-- {{uploadconfig.url}} -->
				<!-- 图片上传模块 -->
				<uni-forms-item label="里程图片"></uni-forms-item>
				
				<uni-row>
					<uni-col :span="8" v-for="(item, idx) in jiayouApplyForm.pics" :key="idx">
						<view class="img-res" @click="showBigImg(jiayouApplyForm.pics,idx)">
							<image :src="jiayouApplyForm.pics[idx]" :key="idx" />
						</view>
					</uni-col>
				</uni-row>
				<button @click="clickSelectPic" class="btn-add">选择图片</button>

				<!-- 选人模块 -->
				<uni-forms-item label="审核人" required></uni-forms-item>
				<view v-for="(item, idx) in jiayouApplyForm.auditors" :key="idx">
					<uni-row>
						<uni-col :span="10">
							<view v-if="idx>0" class="step-arrow">
								<uni-icons type="bottom" size="mini" color='#a5eaff'></uni-icons>
							</view>
						</uni-col>
					</uni-row>
				
					<view class="step">
						<uni-row>
							<uni-col :span="10">
								<view class="step-info-left">{{item.stepName || item.positionName}}</view>
							</uni-col>
							<uni-col :span="14">
								<view class="step-info-right">{{item.name}}</view>
							</uni-col>
						</uni-row>
					</view>
				</view>

				<view style="padding-top: 30px;"></view>
				<button type="primary" @click="clickApply">提交</button>
			</uni-forms>
		</view>
		<view v-if="currentIndex === 1">
			<view v-for="(item, idx) in applyRecord" style="padding-bottom: 10px;" :key="idx">
				<view class="card" @click="seeDetail(idx)">
					<view class="card-title">
						<uni-row>
							<uni-col :span="20">
								<view class="card-title-left">{{item.chepai}}</view>
							</uni-col>
							<uni-col :span="4">
								<view class="card-title-right">
									<uni-tag text="审核" size="mini" type="warning" v-if="item.sta===0&&item.chexiao==0"></uni-tag>
									<uni-tag text="通过" size="mini" type="primary" v-if="item.sta===1&&item.chexiao==0"></uni-tag>
									<uni-tag text="拒绝" size="mini" type="error" v-if="item.sta===2&&item.chexiao==0"></uni-tag>
									<uni-tag text="撤销" size="mini" type="default" v-if="item.chexiao===1"></uni-tag>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="card-body">
						<view>部门：{{item.department}}</view>
						<view>加油时间：{{item.jiayouDate}}</view>
						<view>上次里程：{{item.lastLicheng}}</view>
						<view>本次里程：{{item.licheng}}</view>
					</view>
					<view class="card-footer">
						<uni-row>
							<uni-col :span="24">
								<view class="card-footer-right">
									{{getFormatedTimeStr(item.createTime)}}
								</view>
							</uni-col>
						</uni-row>
					</view>
				</view>
			</view>

			<uni-load-more :status="moreStatus"></uni-load-more>
		</view>

	</view>
</template>

<script>
	import {
		websock
	} from '../../net/websock'
	import moment from 'moment'
	import store from '../../store'
	import {
		uploadconfig
	} from '../../const'
	import { quchongAuditors } from '../../utils/util'

	export default {
		data() {
			return {
				// 上传参数部分没有事情不要乱动
				uploadconfig,
				option: {
					url: uploadconfig.url,
					name: 'file',
					header: {},
					formData: {}
				},
				formats: uploadconfig.formats,
				instantly: uploadconfig.instantly,
				size: uploadconfig.size,
				files: new Map(),
				// 上传参数部分没有事情不要乱动
				currentIndex: 0,
				items: ['加油申请', '加油记录'],
				departNames: [],
				departIds: [],
				departIndex: 0,
				userName: '',
				userInfo: {},
				chepaiList: [],
				chepaiIndex: 0,
				moreStatus: 'more',
				applyRecord: [],
				wanzhengStr: [{
					text: "否",
					value: 0
				}, {
					text: "是",
					value: 1
				}],
				jiayouApplyForm: {
					department: 0, // 申请部门
					jiayouDate: 0,
					chepai: '',
					licheng: '',
					lastLicheng: '',
					pics: [],
					wanzheng: 0,
					auditors: []
				}
			}
		},
		async onReady() {
			console.log('jiayou shenqing on ready')

			try {
				this.userInfo = await websock.getUserInfo()
				this.userName = this.userInfo.name

				let departList = await websock.getDepartList()
				for (let i = 0; i != departList.length; i++) {
					if (departList[i].id == 1) continue
					this.departNames.push(departList[i].name)
					this.departIds.push(departList[i].id)
				}
				console.log('depart list', departList)

				this.jiayouApplyForm.jiayouDate = moment().format('YYYY-MM-DD')

				let chepaiList = await websock.chepaiList()
				for (let i = 0; i != chepaiList.length; i++) {
					this.chepaiList.push(chepaiList[i].name)
				}

				let auditors = await websock.getAuditors({typ: 9})
				console.log('auditors', auditors)
				quchongAuditors(auditors)
				this.jiayouApplyForm.auditors = auditors

				this.getNewestRecord()
			} catch (e) {
				uni.showToast({
					title: e.message
				})
			}
		},
		// 下拉刷新，获取最新的数据
		onPullDownRefresh() {
			console.log('onPullDownRefresh')
			if (this.currentIndex == 0) {
				uni.stopPullDownRefresh()
			} else {
				this.getNewestRecord()
			}
		},
		// 上拉刷新，获取历史数据
		onReachBottom() {
			console.log('onReachBottom')
			if (this.currentIndex == 1) {
				this.getOlderRecord()
			}
		},
		methods: {
			// 获取最新的通知
			async getNewestRecord() {
				try {
					if (this.applyRecord.length == 0) {
						let res = await websock.jiayouApplyRecord({
							pageCount: 10
						})
						console.log('getRecordList list empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					} else {
						let res = await websock.jiayouApplyRecord({
							greaterThan: this.applyRecord[0].id,
							pageCount: 10
						})
						console.log('getRecordList list not empty', res)
						uni.stopPullDownRefresh()
						this.applyRecord = [...res, ...this.applyRecord]
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			// 获取老的数据
			async getOlderRecord() {
				this.moreStatus = 'loading'
				try {
					if (this.applyRecord.length == 0) {
						console.log('before get list empty')
						let res = await websock.jiayouApplyRecord({
							pageCount: 10
						})
						console.log('getOlderRecord list empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					} else {
						console.log('before get list not empty')
						let res = await websock.jiayouApplyRecord({
							lessThan: this.applyRecord[this.applyRecord.length - 1].id,
							pageCount: 10
						})
						console.log('getOlderRecord list not empty', res)
						this.applyRecord = [...this.applyRecord, ...res]
						if (res.length < 10) {
							this.moreStatus = 'noMore'
						} else {
							this.moreStatus = 'more'
						}
					}
				} catch (e) {
					uni.showToast({
						title: e.message
					})
				}
			},
			onClickItem(e) {
				if (this.currentIndex !== e.currentIndex) {
					this.currentIndex = e.currentIndex
				}
			},
			departChange(e) {
				console.log('depart change', e.detail.value)
				this.departIndex = e.detail.value
			},
			departNameStr() {
				return this.departNames[this.departIndex] || ''
			},

			chepaiChange(e) {
				this.chepaiIndex = e.detail.value
			},
			chepaiNameStr() {
				return this.chepaiList[this.chepaiIndex] || ''
			},
			clickSelectAuditor() {
				uni.navigateTo({
					url: '/pages/common/contactSelect?selectedUsers=' + JSON.stringify(this.jiayouApplyForm .auditors || []),
					events: {
						contactList: data => {
							console.log('select auditor', data)
							this.jiayouApplyForm.auditors = data.contactList
						}
					}
				})
			},
			// 获取格式化时间字符串
			getFormatedTimeStr(stamp, str='MM-DD HH:mm:ss') {
				return moment(stamp).format(str)
			},
			// 选择图片
			clickSelectPic() {
				uni.chooseImage({
					count: 9, //选择图片数
					sourceType: ['camera', 'album'], //从相册还是相机选择
					success: (res) => {
						for (let path in res.tempFilePaths) {
							uni.uploadFile({
								url: this.uploadconfig.url,
								filePath: res.tempFilePaths[path],
								name: 'file',
								formData: {
									uid: this.userInfo.uid,
									token: store.token
								},
								success: res => {
									try {
										let data = JSON.parse(res.data)
										if (data.code != 0) {
											return uni.showToast({
												title: data.message
											})
										}
										this.jiayouApplyForm.pics.push(data.data)
									} catch (e) {
										console.error(e)
										uni.showToast({
											title: '上传图片失败' + e.message
										})
									}
									console.log('success', res)
								},
								fail: (res) => {
									uni.showToast({
										title: '上传图片失败' + res
									})
								},
								complete: () => {
									console.log('uploa file complete')
								}
							})
						}
			
					}
				})
			},
			//点击放大图片
			showBigImg(imgurl, cur) {
				uni.previewImage({
					current: cur,
					loop: true,
					urls: imgurl,
				})
			},

			async clickApply() {
				console.log('click apply', this.jiayouApplyForm)

				if (!this.jiayouApplyForm.licheng) return uni.showToast({
					title: '请输入本次里程'
				})
				if (!this.jiayouApplyForm.lastLicheng) return uni.showToast({
					title: '请输入上次里程'
				})
				if (this.jiayouApplyForm.pics.length == 0) return uni.showToast({
					title: '请选择里程图片'
				})
				if (this.jiayouApplyForm.auditors.length == 0) return uni.showToast({
					title: '请选择审核人'
				})

				let auditors = []
				for (let i = 0; i != this.jiayouApplyForm.auditors.length; i++) {
					auditors.push({uid: this.jiayouApplyForm.auditors[i].uid, stepName: this.jiayouApplyForm.auditors[i].stepName || this.jiayouApplyForm.auditors[i].positionName})
				}

				try {
					await websock.jiayouApply({
						department: this.userInfo.departmentName,
						jiayouDate: this.jiayouApplyForm.jiayouDate,
						chepai: this.chepaiList[this.chepaiIndex],
						licheng: this.jiayouApplyForm.licheng,
						lastLicheng: this.jiayouApplyForm.lastLicheng,
						pics: this.jiayouApplyForm.pics,
						wanzheng: this.jiayouApplyForm.wanzheng,
						auditors
					})

					uni.showToast({
						title: '提交成功'
					})

					this.jiayouApplyForm = {
						department: 0, // 申请部门
						jiayouDate: '',
						chepai: '',
						licheng: '',
						lastLicheng: '',
						pics: [],
						wanzheng: 0,
						auditors: []
					}

					this.currentIndex = 1

					this.getNewestRecord()
				} catch (err) {
					uni.showToast({
						title: err.message
					})
				}
			},
			async revertApply(idx) {
				try {
					await websock.revertJiayouApply({
						id: this.applyRecord[idx].id
					})
					this.applyRecord[idx].sta = 4
				} catch (err) {
					console.error(err)
					uni.showToast({
						title: err.message || 'error'
					})
				}
			},
			seeDetail(idx) {
				uni.navigateTo({
					url: `/pages/task/jiayouApplyDetail?id=${this.applyRecord[idx].id}`
				})
			}
		}
	}
</script>

<style>
	@import '../common/common.css';
</style>
